package cn.interestingshop.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

/**
 * @ClassName : EncodeFilter
 * @Description :
 * @Author : Lzz
 * @Date: 2023/2/17 16:57:00
 */
@WebFilter(urlPatterns = {"/*"},filterName = "EncodeFilter",initParams = {@WebInitParam(name = "encode",value = "utf-8")})
public class EncodeFilter implements Filter {

    private String encode = null;   //字符集编码

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String encode = filterConfig.getInitParameter("encode");    //获取initParameter初始化的值
        if(this.encode == null){
            this.encode = encode;
        }

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if(servletRequest.getCharacterEncoding() == null){
            servletRequest.setCharacterEncoding(encode);
        }
        filterChain.doFilter(servletRequest, servletResponse); //放行请求
    }

    @Override
    public void destroy() {
        System.out.println("执行destroy()....");
    }
}
